<template>
  <div class="dashboard-container">
    <el-row>
      起始日期:
      <el-date-picker
        v-model="dateRange[0]"
        :editable="false"
        style="width: 180px"
        type="date"
        align="right"
        unlink-panels
        :clearable="false"
        value-format="yyyy-MM-dd"
        :picker-options=" {disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6
        }}"
      />
      结束日期:
      <el-date-picker
        v-model="dateRange[1]"
        readonly
        style="width: 180px"
        :editable="false"
        type="date"
        align="right"
        unlink-panels
        :clearable="false"
        value-format="yyyy-MM-dd"
      />
      共{{ days }}日
    </el-row>
    <el-row style="margin: 12px 0;">
      选择产线:
      <el-select v-model="lineList" multiple placeholder="请选择产线" :multiple-limit="3" style="width: 60%">
        <el-option
          v-for="item in myLineList"
          :key="item.lid"
          :label="item.name"
          :value="item.lid"
        >
        </el-option>
      </el-select>
      <el-button style="margin-left: 8px;" type="primary" icon="el-icon-search" size="small" @click="query">查询
      </el-button>
    </el-row>
    <el-row :gutter="8" type="flex" justify="space-between" style="flex-wrap: wrap;">
      <el-col :span="8" style="margin-top:4px;">
        <el-card shadow="always" style="cursor: pointer; width: 100%"
                 @click.native="$router.push({path:'/workOrderSys/todoOrder'})"
        >
          <el-row style="height:100%;align-items:center;" type="flex" justify="space-between">
            <el-col :span="6" style="margin-right: 6px;">
              <svg-icon class-name="my-icon" icon-class="order-processing"
                        style="color:orangered; font-size: 44px"
              />
            </el-col>
            <el-col :span="16"
                    style="font-size:16px; color: #5a5e66; height:100%;display:flex;text-align:start;align-items:center;"
            >
              <el-row style="height:100%;width:100%;flex-direction: column;align-items: flex-end;" type="flex"
                      justify="center"
              >
                <div>
                  <div style="width: 100%;text-align: left; font-size: 16px;">待办工单</div>
                  <div style="width: 100%;text-align: left; font-size: 20px; font-weight: bold;">
                    {{ orderCount.ToDOOrderNums }}
                  </div>
                </div>
              </el-row>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="8" style="margin-top:4px;">
        <el-card shadow="always" style="cursor: pointer; width: 100%"
                 @click.native="$router.push({path:'/workOrderSys/myCreation'})"
        >
          <el-row style="height:100%;align-items:center;" type="flex" justify="space-between">
            <el-col :span="6" style="margin-right: 6px;">
              <i class="el-icon-document-add" style="color:dodgerblue; font-size: 44px"/>
            </el-col>
            <el-col :span="16"
                    style="font-size:16px; color: #5a5e66; height:100%;display:flex;text-align:start;align-items:center;"
            >
              <el-row style="height:100%;width:100%;flex-direction: column;align-items: flex-end;" type="flex"
                      justify="center"
              >
                <div>
                  <div style="width: 100%;text-align: left; font-size: 16px;">我创建的</div>
                  <div style="width: 100%;text-align: left; font-size: 20px; font-weight: bold;">
                    {{ orderCount.MyCreateOrderNums }}
                  </div>
                </div>
              </el-row>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="8" style="margin-top:4px;">
        <el-card shadow="always" style="cursor: pointer; width: 100%">
          <el-row style="height:100%;align-items:center;" type="flex" justify="space-between"
                  @click.native="$router.push({path:'/workOrderSys/myRelated'})"
          >
            <el-col :span="6" style="margin-right: 6px;">
              <i class="el-icon-document-copy" style="color:saddlebrown; font-size: 44px"/>
            </el-col>
            <el-col :span="16"
                    style="font-size:16px; color: #5a5e66; height:100%;display:flex;text-align:start;align-items:center;"
            >
              <el-row style="height:100%;width:100%;flex-direction: column;align-items: flex-end;" type="flex"
                      justify="center"
              >
                <div>
                  <div style="width: 100%;text-align: left; font-size: 16px;">我相关的</div>
                  <div style="width: 100%;text-align: left; font-size: 24px; font-weight: bold;">
                    {{ orderCount.MyRelateOrderNums }}
                  </div>
                </div>
              </el-row>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="8" type="flex" justify="space-between" style="flex-wrap: wrap;">
      <el-col :span="8" style="margin-top:4px;">
        <el-card shadow="always" style="cursor: pointer; width: 100%;;"
                 @click.native="$router.push({path:'/staffingSys/userManage'})"
        >
          <el-row style="height:100%;align-items:center;" type="flex" justify="space-between">
            <el-col :span="6" style="margin-right: 6px;">
              <svg-icon class-name="my-icon" icon-class="dashboard-users"
                        style="color:lightseagreen; font-size: 44px"
              />
            </el-col>
            <el-col :span="16"
                    style="font-size:16px; color: #5a5e66; height:100%;display:flex;text-align:start;align-items:center;"
            >
              <el-row style="height:100%;width:100%;flex-direction: column;align-items: flex-end;" type="flex"
                      justify="center"
              >
                <div>
                  <div style="width: 100%;text-align: left; font-size: 16px;">用户总数</div>
                  <div style="width: 100%;text-align: left; font-size: 20px; font-weight: bold;">
                    {{ orderCount.AllUserNums }}
                  </div>
                </div>
              </el-row>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="8" style="margin-top:4px;">
        <el-card shadow="always" style="cursor: pointer; width: 100%"
                 @click.native="$router.push({path:'/staffingSys/orderManage'})"
        >
          <el-row style="height:100%;align-items:center;" type="flex" justify="space-between">
            <el-col :span="6" style="margin-right: 6px;">
              <svg-icon class-name="my-icon" icon-class="order-total"
                        style="color:dodgerblue; font-size: 44px"
              />
            </el-col>
            <el-col :span="16"
                    style="font-size:16px; color: #5a5e66; height:100%;display:flex;text-align:start;align-items:center;"
            >
              <el-row style="height:100%;width:100%;flex-direction: column;align-items: flex-end;" type="flex"
                      justify="center"
              >
                <div>
                  <div style="width: 100%;text-align: left; font-size: 16px;">工单总数</div>
                  <div style="width: 100%;text-align: left; font-size: 20px; font-weight: bold;">
                    {{ orderCount.AllOrderNums }}
                  </div>
                </div>
              </el-row>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="8" style="margin-top:4px;">
        <el-card shadow="always" style="cursor: pointer; width: 100%"
                 @click.native="$router.push({path:'/workOrderSys/todoOrder'})"
        >
          <el-row style="height:100%;align-items:center;" type="flex" justify="space-between">
            <el-col :span="6" style="margin-right: 6px;">
              <svg-icon class-name="my-icon" icon-class="order-processing"
                        style="color:orangered; font-size: 44px"
              />
            </el-col>
            <el-col :span="16"
                    style="font-size:16px; color: #5a5e66; height:100%;display:flex;text-align:start;align-items:center;"
            >
              <el-row style="height:100%;width:100%;flex-direction: column;align-items: flex-end;" type="flex"
                      justify="center"
              >
                <div>
                  <div style="width: 100%;text-align: left; font-size: 16px;">待办总数</div>
                  <div style="width: 100%;text-align: left; font-size: 20px; font-weight: bold;">
                    {{ orderCount.AllToDoOrderNums }}
                  </div>
                </div>
              </el-row>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" style="margin-top:12px;">
        <el-card shadow="always" style="cursor: pointer; width: 100%">
          <div id="daily-stat-graph" style="width: 100%;height: 300px;"/>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="8" type="flex" justify="space-between" style="flex-wrap: wrap;">
      <el-col :span="24" style="margin-top:12px;">
        <el-card shadow="always" style="cursor: pointer; width: 100%">
          <div id="daily-exception-stat-graph" style="width: 100%;height: 300px"/>
        </el-card>
      </el-col>
      <el-col :span="24" style="margin-top:12px;">
        <el-card shadow="always" style="cursor: pointer; width: 100%">
          <div id="exception-reason-graph" style="width: 100%;height: 300px"/>
        </el-card>
      </el-col>
      <el-col :span="24" style="margin-top:12px;">
        <el-card shadow="always" style="cursor: pointer; width: 100%">
          <div id="total_fault_graph" style="width: 100%;height: 300px"/>
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import * as echarts from 'echarts'
import {getOverview} from '@/api/user'
import {getInspection} from '@/api/table'
import {getAllLineList} from '@/api/line'

export default {
  name: 'Dashboard',
  data() {
    return {
      lineList: [],
      myLineList: [],
      dateRange: '',
      problemReason: null,
      dailyStatGraph: null,
      ExceptionReasonGraph: null,
      DailyExceptionStatGraph: null,
      TotalFaultGraph: null,
      orderCount: {
        'AllOrderNums': 0,
        'ToDOOrderNums': 0,
        'AllToDoOrderNums': 0,
        'AllUserNums': 3,
        'MyCreateOrderNums': 0,
        'MyRelateOrderNums': 0
      },
      overViewData: [],
      problemData: []
    }
  },
  computed: {
    nameList() {
      let rt = []
      for (let i = 0; i < this.lineList.length; i++) {
        rt.push(this.myLineList.find((line) => line.lid === this.lineList[i]).name)
      }
      return rt
    },
    ...mapGetters([
      'name'
    ]),
    days() {
      const myDate_1 = Date.parse(this.dateRange[0])
      const myDate_2 = Date.parse(this.dateRange[1])
      const diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值
      // 向下取整
      return Math.floor(diffDate / (1000 * 3600 * 24))
    }
  },
  watch: {
    '$store.getters.sidebar.opened': {
      handler: function() {
        setTimeout(() => {
          this.dailyStatGraph.resize()
          this.ExceptionReasonGraph.resize()
          this.DailyExceptionStatGraph.resize()
          this.TotalFaultGraph.resize()
        }, 280)
      }
    }
  },
  created() {

  },
  async mounted() {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
    this.dateRange = [start, end]
    //获取我的全部line 列表
    await getAllLineList().then(res => {
      this.myLineList = res.data
    })
    this.lineList.push(this.$store.getters.lid)
    await getOverview().then(res => {
      this.overViewData.push(res.data)
      this.orderCount = {
        'AllOrderNums': res.data.AllOrderNums,
        'ToDOOrderNums': res.data.ToDOOrderNums,
        'AllToDoOrderNums': res.data.AllToDoOrderNums,
        'AllUserNums': res.data.AllUserNums,
        'MyCreateOrderNums': res.data.MyCreateOrderNums,
        'MyRelateOrderNums': res.data.MyRelateOrderNums
      }
      this.createExceptionReasonGraph()
    })
    await getInspection().then(res => {
      this.problemData.push(res.data)
      this.createDailyStatGraph()
      this.creatDailyExceptionStatGraph()
      this.createTotalFaultGraph()
    })
  },
  methods:
    {
      query() {
        let promiseList = []
        for (let i = 0; i < this.lineList.length; i++) {
          promiseList.push(getOverview({range: this.days, lid: this.lineList[i]}))
        }
        if (promiseList.length === 0) {
          this.$message({
            message: '请选择产线',
            type: 'warning'
          })
          return
        }
        this.overViewData = []
        Promise.all(promiseList).then(res => {
          this.orderCount = res.map(item => item.data).reduce((pre, cur) => {
            return {
              'AllOrderNums': cur.AllOrderNums,
              'ToDOOrderNums': cur.ToDOOrderNums,
              'AllToDoOrderNums': cur.AllToDoOrderNums,
              'AllUserNums': cur.AllUserNums,
              'MyCreateOrderNums': cur.MyCreateOrderNums,
              'MyRelateOrderNums': cur.MyRelateOrderNums
            }
          })
          this.overViewData = res.map(item => item.data)
          this.createExceptionReasonGraph()
        })
        //获取Inspection
        promiseList = []
        for (let i = 0; i < this.lineList.length; i++) {
          promiseList.push(getInspection({range: this.days, lid: this.lineList[i]}))
        }
        Promise.all(promiseList).then(res => {
          this.problemData = res.map(item => item.data)
          this.createDailyStatGraph()
          this.creatDailyExceptionStatGraph()
          this.createTotalFaultGraph()
        })
      },
      createDailyStatGraph() {
        // const app = {}
        const chartDom = document.getElementById('daily-stat-graph')
        const myChart = echarts.init(chartDom)
        this.dailyStatGraph = myChart
        myChart.resize()

        // const categories = (function() {
        //   let now = new Date()
        //   const res = []
        //   let len = 10
        //   while (len--) {
        //     res.unshift(now.toLocaleTimeString().replace(/^\D*/, ''))
        //     now = new Date(+now - 2000)
        //   }
        //   return res
        // })()
        const categories = this.problemData[0].map((item) => {
          return item.time
        })
        // const categories2 = (function() {
        //   const res = []
        //   let len = 10
        //   while (len--) {
        //     res.push(10 - len - 1)
        //   }
        //   return res
        // })()
        const categories2 = this.problemData[0].map((item, index) => {
          return index
        })
        // const data = this.problemData.map((item) => {
        //   return item.count
        // })
        const dataCount = []
        for (let i = 0; i < this.problemData.length; i++) {
          dataCount.push(this.problemData[i].map((item) => {
            return item.count
          }))
        }

        //计算最大值
        let countMax = 0
        for (let i = 0; i < dataCount.length; i++) {
          if (Math.max(...dataCount[i]) > countMax) {
            countMax = Math.max(...dataCount[i])
          }
        }

        const dataProblem = []
        for (let i = 0; i < this.problemData.length; i++) {
          dataProblem.push(this.problemData[i].map((item) => {
            return item.problem
          }))
        }

        let problemMax = 0
        for (let i = 0; i < dataProblem.length; i++) {
          if (Math.max(...dataProblem[i]) > problemMax) {
            problemMax = Math.max(...dataProblem[i])
          }
        }

        const option = {
          title: {
            text: '日提检台数与日缺陷数'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#283b56'
              }
            }
          },
          legend: {
            orient: 'horizontal',
            x: 'right',
            y: 'top',
            padding: [10, 60, 0, 0]
            // data: ['提检数（台）', '缺陷数（个）']
          },
          toolbox: {
            show: true,
            feature: {
              dataView: {readOnly: true},
              saveAsImage: {}
            }
          },
          dataZoom: {
            show: false,
            start: 0,
            end: 100
          },
          grid: {
            top: '20%',
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              boundaryGap: true,
              data: categories
            },
            {
              type: 'category',
              boundaryGap: true,
              data: categories2
            }
          ],
          yAxis: [
            {
              type: 'value',
              scale: true,
              name: '提检数（台）',
              max: countMax,
              min: 0,
              boundaryGap: [0.2, 0.2]
            },
            {
              type: 'value',
              scale: true,
              name: '缺陷数（个）',
              max: problemMax,
              min: 0,
              boundaryGap: [0.2, 0.2]
            }
          ],
          series: (() => {
            let rt = []
            for (let i = 0; i < this.problemData.length; i++) {
              rt.push(
                {
                  name: `${this.nameList[i]}产线提检数`,
                  type: 'bar',
                  data: dataCount[i]
                }
              )
              rt.push(
                {
                  name: `${this.nameList[i]}产线缺陷数`,
                  type: 'line',
                  xAxisIndex: 1,
                  yAxisIndex: 1,
                  data: dataProblem[i]
                }
              )
            }
            console.log(rt)
            return rt
          })()
          // {
          //   name: '提检数（台）',
          //   type: 'bar',
          //   data: data
          // },
          // {
          //   name: '缺陷数（个）',
          //   type: 'line',
          //   xAxisIndex: 1,
          //   yAxisIndex: 1,
          //   data: data2
          // }

        }
        // app.count = 11
        // setInterval(function() {
        //   const axisData = new Date().toLocaleTimeString().replace(/^\D*/, '')
        //   data.shift()
        //   data.push(Math.round(Math.random() * 1000))
        //   data2.shift()
        //   data2.push(+(Math.random() * 10 + 5).toFixed(1))
        //   categories.shift()
        //   categories.push(axisData)
        //   categories2.shift()
        //   categories2.push(app.count++)
        //   myChart.setOption({
        //     xAxis: [
        //       {
        //         data: categories
        //       },
        //       {
        //         data: categories2
        //       }
        //     ],
        //     series: [
        //       {
        //         data: data
        //       },
        //       {
        //         data: data2
        //       }
        //     ]
        //   })
        // }, 60000)
        option && myChart.setOption(option)
      },
      creatDailyExceptionStatGraph() {
        const chartDom = document.getElementById('daily-exception-stat-graph')
        const myChart = echarts.init(chartDom)
        this.DailyExceptionStatGraph = myChart
        myChart.resize()
        const option = {
          title: {
            text: '日台缺陷数'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            orient: 'horizontal',
            x: 'right',
            y: 'top',
            padding: [10, 60, 0, 0]
            // data: ['台缺陷数目标值', '台缺陷数']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          toolbox: {
            show: true,
            feature: {
              dataView: {readOnly: true},
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: true,
            data: this.problemData[0].map((item) => item.time)
            // axisLabel: {
            //   //  X 坐标轴标签相关设置，写在xAxis里面
            //   interval: 0, // 全部标签显示
            //   rotate: '45'// 标签倾斜度数
            // }
          },
          yAxis: {
            type: 'value'
          },
          series: (() => {
            let rt = []
            rt.push(
              {
                name: '台缺陷数目标值',
                type: 'line',
                data: this.problemData[0].map((item) => item.target)
              }
            )
            for (let i = 0; i < this.problemData.length; i++) {
              rt.push(
                {
                  name: `${this.nameList[i]}产线台缺陷数`,
                  type: 'line',
                  data: this.problemData[i].map((item) => item.result)
                }
              )
            }
            console.log(rt)
            return rt
          })()
          // series: [
          //   {
          //     name: '台缺陷数目标值',
          //     type: 'line',
          //     // stack: 'Total',
          //     data: this.problemData.map((item) => item.target)
          //   }
          //   // {
          //   //   name: '台缺陷数',
          //   //   type: 'line',
          //   //   // stack: 'Total',
          //   //   data: this.problemData.map((item) => item.result)
          //   // }
          // ]
        }
        option && myChart.setOption(option)
      },
      createExceptionReasonGraph() {
        const chartDom = document.getElementById('exception-reason-graph')
        const myChart = echarts.init(chartDom)
        this.ExceptionReasonGraph = myChart
        const that = this
        myChart.resize()
        const option = {
          legend: {
            orient: 'horizontal',
            x: 'right',
            y: 'top',
            padding: [10, 60, 0, 0]
            // data: ['台缺陷数目标值', '台缺陷数']
          },
          title: {
            text: `近${this.days}日缺陷原因数`
          },
          tooltip: {
            trigger: 'axis'
          },
          toolbox: {
            show: true,
            feature: {
              dataView: {readOnly: true},
              saveAsImage: {}
            }
          },
          grid: {
            top: '20%',
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: ['卡滞', '分合', '特性', '掉漆', '采购品', '后事故', '其他'],
            triggerEvent: true,
            axisLabel: {
              textStyle: {
                color: '#409EFF',
                fontSize: 14,
                backgroundColor: {
                  image: '',
                  width: 100,
                  height: 40
                }
              }
            }
          },
          yAxis: {
            type: 'value'
          },
          series: (() => {
            let rt = []
            for (let i = 0; i < this.lineList.length; i++) {
              rt.push({
                name: `${this.nameList[i]}产线台缺陷数`,
                data: [this.overViewData[i].SevenDayFaultClass['kazhi'], this.overViewData[i].SevenDayFaultClass.fenhe,
                  this.overViewData[i].SevenDayFaultClass.texing, this.overViewData[i].SevenDayFaultClass.diaoqi,
                  this.overViewData[i].SevenDayFaultClass.caigoupin, this.overViewData[i].SevenDayFaultClass.houshigu,
                  this.overViewData[i].SevenDayFaultClass.qita],
                type: 'bar'
              })
            }
            return rt
          })()
        }
        option && myChart.setOption(option)
        myChart.on('click', 'xAxis.category', function(params) {
          that.$router.push({path: '/workOrderSys/problemOrder', query: {pid: params.dataIndex + 1}})
        })
      },
      createTotalFaultGraph() {
        //total_fault_graph 柱状图
        const chartDom = document.getElementById('total_fault_graph')
        const myChart = echarts.init(chartDom)
        this.TotalFaultGraph = myChart
        myChart.resize()
        let option = {
          title: {
            text: `近${this.days}日缺陷对比`
          },
          xAxis: {
            type: 'category',
            data: this.nameList
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: (() => {
                let rt = []
                for (let i = 0; i < this.lineList.length; i++) {
                  //SevenDayFaultClass是个对象，把每一个属性的值加起来
                  let sum = 0
                  for (let key in this.overViewData[i].SevenDayFaultClass) {
                    sum += this.overViewData[i].SevenDayFaultClass[key]
                  }
                  rt.push(sum)
                }
                return rt
              }),
              type: 'bar'
            }
          ]
        }
        option && myChart.setOption(option)

      }
    }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.my-icon {
  font-size: 50px;
}
</style>
